<template>
  <div class="total-table-container">
    <div class="bottom-chart-header">
      <div class="header-column">
        <span class="header-column-title">订单类型:</span>
        <a-select show-search :value="billTypeValue" placeholder="请选择" option-filter-prop="children" style="width: 67%; margin-top: 30px" @change="handleBillChange">
          <a-select-option value="all">
            全部
          </a-select-option>
          <a-select-option value="我的">
            我的
          </a-select-option>
          <a-select-option value="研究院工单">
            研究院工单
          </a-select-option>
        </a-select>
      </div>
      <div class="header-column" v-show="isSearchShow">
        <span class="header-column-title">完成状态:</span>
        <a-select show-search v-model="finishTypeValue" placeholder="请选择" option-filter-prop="children" style="width: 67%; margin-top: 30px" @change="handleFinishChange">
          <a-select-option value="已完成订单">
            已完成订单
          </a-select-option>
          <a-select-option value="未完成订单">
            未完成订单
          </a-select-option>
        </a-select>
      </div>
      <div class="header-column" v-show="isSearchShow">
        <span class="header-column-title">订单状态:</span>
        <a-select show-search v-model="stateTypeValue" placeholder="请选择" option-filter-prop="children" style="width: 67%; margin-top: 30px" @change="handleStateChange">
          <a-select-option value="-1">
            全部
          </a-select-option>
          <a-select-option value="1">
            已报单
          </a-select-option>
          <a-select-option value="2">
            已指派
          </a-select-option>
          <a-select-option value="8">
            进行中
          </a-select-option>
          <a-select-option value="9">
            工单暂停
          </a-select-option>
          <a-select-option value="5">
            待回访
          </a-select-option>
          <a-select-option value="6">
            已关闭
          </a-select-option>
        </a-select>
      </div>
      <div class="header-column" v-show="isSearchShow">
        <a-input placeholder="请输入" v-model="searchInput" class="mend-search-input" />
        <div class="mend-search-button" @click="searchParam">
          <a-icon type="search" class="icon" />
        </div>
      </div>
      <div class="header-column" v-show="isSearchShow">
        <div class="mend-advanced-search" @click="handleAdvancedSearch">高级搜索</div>
      </div>
    </div>

    <div style="padding:8px 16px">
      <a-row>
        <a-col :span="2" push="22" style="text-align: right;">
          <ExportFile :fetch="getDownloadData" :fields="jsonFields" name="downloadFile.xls">
            <a-button class="editable-add-btn" type="primary" :loading="iconLoading" :disabled="isLoading">导出</a-button>
          </ExportFile>
        </a-col>
      </a-row>
    </div>

    <a-table
      :columns="columns"
      :data-source="tableData"
      :loading="isLoading"
      :pagination="pagination"
      bordered
      class="single-table"
      :scroll="{ x: 1200 }"
      @change="tableChange"
      :customRow="clickSingleRow"
      id="mendListTable"
    >
      <template slot="state" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <span v-if="record.state === 1">已报单</span>
          <span v-if="record.state === 2">已指派</span>
          <span v-if="record.state === 8">进行中</span>
          <span v-if="record.state === 9">工单暂停</span>
          <span v-if="record.state === 5">待回访</span>
          <span v-if="record.state === 6">已关闭</span>
          <span v-if="record.state === 4">已关闭</span>
          <span v-if="record.state === 10">内部已关闭</span>
          <span v-if="record.state === 11">已指派</span>
        </div>
      </template>

      <template slot="newBill" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <span v-if="record.suit === 'true' && (record.state === 2 || record.state === 3)">
            <a-icon
              type="plus-circle"
              class="mend-plus-circle"
              @click.stop="
                () => {
                  handleNewBill(record);
                }
              "
            />
          </span>
        </div>
      </template>

      <template slot="isViIssue" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <span v-if="record.isViIssue === 'true'">
            <span>是&nbsp; {{ record.viIssueInfo }}</span>
          </span>
          <span v-if="record.isViIssue === 'false'">
            <span>否</span>
          </span>
          <span v-if="!record.isViIssue">
            <span></span>
          </span>
        </div>
      </template>

      <template slot="operation" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <span v-if="record.state === 1 && (role === 17 || role === 19)">
            <a-button
              type="primary"
              @click.stop="
                () => {
                  handleDispatch(record);
                }
              "
              >指派</a-button
            >
            <a-button
              type="danger"
              @click.stop="
                () => {
                  handleDelete(record);
                }
              "
              >删除</a-button
            >
          </span>
          <span v-if="record.state === 1 && (role === 18 || role === 20 || role === 6 || role === 21)">
            <a-button
              type="primary"
              @click.stop="
                () => {
                  handleDispatch(record);
                }
              "
              >指派</a-button
            >
          </span>
          <span v-if="record.suit === 'false' && (record.state === 2 || record.state === 8 || record.state === 9) && (role === 17 || role === 19 || role === 18 || role === 20)">
            <a-button
              type="primary"
              @click.stop="
                () => {
                  handleTransfer(record);
                }
              "
              class="mend-transfer"
              >转单</a-button
            >
            <!--此处一定要注销-->
            <!--<a-button type="primary" @click.stop="() => {handleFinish(record)}">维修完成</a-button>-->
          </span>
          <span v-if="record.suit === 'true' && record.state === 2 && (role === 17 || role === 19 || role === 18 || role === 20 || role === 6 || role === 21)">
            <a-button
              type="primary"
              @click.stop="
                () => {
                  handleTransfer(record);
                }
              "
              class="mend-transfer"
              >转单</a-button
            >
          </span>

          <span v-if="record.suit === 'true' && (record.state === 8 || record.state === 9) && (role === 6 || role === 21 || role === 18 || role === 20 || role === 17 || role === 19)">
            <a-button
              type="primary"
              @click.stop="
                () => {
                  handleFinish(record);
                }
              "
              >维修完成</a-button
            >
            <a-button
              type="primary"
              @click.stop="
                () => {
                  handleTransfer(record);
                }
              "
              class="mend-transfer"
              >转单</a-button
            >
          </span>
          <span v-if="record.state === 4 || (record.state === 6 && (role === 17 || role === 19))">
            <a-button
              type="primary"
              @click.stop="
                () => {
                  handleInnerClose(record);
                }
              "
              >内部关闭</a-button
            >
          </span>

          <span v-if="record.state === 5 && (role === 17 || role === 19)">
            <a-button
              type="primary"
              class="mend-evaluate"
              @click.stop="
                () => {
                  handleEvaluate(record);
                }
              "
              >评价</a-button
            >
          </span>
        </div>
      </template>

      <template slot="afterSaleNumber" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <span v-if="record.afterSaleNumber === ''" class="update-button">
            <img src="@/images/agent_service.png" />
          </span>
          <span v-if="record.afterSaleNumber !== ''" class="update-button"> <img src="@/images/agent_service.png" />&nbsp;&nbsp;<img src="@/images/hzncc_service.png" /> </span>
        </div>
      </template>
    </a-table>

    <a-modal v-model="visible" title="工单指派" class="dispatch-modal" okText="确定" cancelText="取消" @ok="handleDispatchOk">
      <div class="dispatch-modal-container">
        <div class="mend-single-row">
          <span class="dispatch-must" style="line-height: 30px">✻</span>
          <span style="width: 100px; line-height: 30px">工程师姓名:</span>
          <a-select
            show-search
            :default-value="dispatchList[0].id"
            placeholder="请选择"
            option-filter-prop="children"
            style="width: 62%"
            :filter-option="filterOption"
            @focus="handleFocus"
            @blur="handleBlur"
            @change="handleDispatchChange"
          >
            <a-select-option v-for="(dispatchItem, index) in dispatchList" :key="index" :value="dispatchItem.id">
              {{ dispatchItem.name }}
            </a-select-option>
          </a-select>
        </div>
        <div class="mend-single-row">
          <span class="dispatch-must" style="line-height: 75px">✻</span>
          <span style="width: 100px; line-height: 75px">工程师电话:</span>
          <a-input v-model="dispatchPhone || dispatchList[0].username" class="dispatch-input-container" readOnly />
        </div>
      </div>
    </a-modal>

    <a-modal v-model="transferModel" title="转单" class="transfer-modal" okText="确定" cancelText="取消" @ok="handleTransferOk" @cancel="handleTransferCancel">
      <div class="dispatch-modal-container">
        <a-form :form="transferForm">
          <div class="mend-transfer-single-row">
            <a-col span="24" className="service-form">
              <a-form-item label="工程师姓名:" class="repair-form">
                <a-select
                  option-filter-prop="children"
                  show-search
                  @change="handleTransferChange"
                  style="width: 100%"
                  v-decorator="['repairMan', { initialValue: transferList[0].iD, rules: [{ required: false, message: '' }] }]"
                  placeholder="请选择"
                >
                  <a-select-option v-for="(dispatchItem, index) in transferList" :key="index" :value="dispatchItem.iD">
                    {{ dispatchItem.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </div>
          <div class="mend-transfer-single-row">
            <a-col span="24" className="service-form">
              <a-form-item label="工程师电话:" class="repair-form">
                <a-input
                  style="width: 100%;"
                  v-decorator="['phoneNumber', { initialValue: transferList[0].username, rules: [{ required: false, message: '' }] }]"
                  placeholder="请输入"
                  autoComplete="off"
                  readOnly
                />
              </a-form-item>
            </a-col>
          </div>
        </a-form>
      </div>
    </a-modal>

    <a-modal v-model="innerModel" title="内部关闭" class="inner-modal" @ok="handleDispatchOk">
      <div class="inner-modal-container">
        <a-result status="info" title="确定内部关闭此售后单?" class="result-info">
          <template #extra>
            <a-button key="console" type="primary" class="inner-sure-btn" @click="handleInnerCloseOk">
              确 定
            </a-button>
            <a-button key="buy" class="inner-cancel-btn" @click="handleInnerCancel">
              取 消
            </a-button>
          </template>
        </a-result>
      </div>
    </a-modal>

    <a-modal v-model="finishModel" title="维修完成" class="inner-modal" @ok="handleDispatchOk">
      <div class="inner-modal-container">
        <a-result status="success" title="确定维修完成吗?" class="result-info">
          <template #extra>
            <a-button key="console" type="primary" class="inner-sure-btn" @click="handleFinishOk">
              确 定
            </a-button>
            <a-button key="buy" class="inner-cancel-btn" @click="handleFinishCancel">
              取 消
            </a-button>
          </template>
        </a-result>
      </div>
    </a-modal>

    <a-modal v-model="evaluateModel" title="评价" class="mend-evaluate-modal" okText="确定" cancelText="取消" @ok="handleEvaluateOk" @cancel="handleEvaluateCancel">
      <div class="mend-evaluate-container">
        <div class="evaluate-header">感谢对本次服务作出评价</div>
        <a-form :form="evaluateForm">
          <div class="evaluate-single-row">
            <a-form-item label="服务满意度" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <span>
                <a-rate v-model="serviceScore" :allow-clear="false" :tooltips="serviceDesc" :count="count" />
                <span class="ant-rate-text">{{ serviceDesc[serviceScore - 1] }}</span>
              </span>
            </a-form-item>
            <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="服务回访备注">
              <a-textarea class="repair-desc" v-decorator="['serviceEvaluate']" placeholder="请输入服务回访备注" style="resize: none;" autoComplete="off" />
            </a-form-item>
            <a-form-item label="产品满意度" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <span>
                <a-rate v-model="produceScore" :allow-clear="false" :tooltips="produceDesc" :count="count" />
                <span class="ant-rate-text">{{ produceDesc[produceScore - 1] }}</span>
              </span>
            </a-form-item>
            <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="产品回访备注">
              <a-textarea class="repair-desc" v-decorator="['produceEvaluate']" placeholder="请输入产品回访备注" style="resize: none;" autoComplete="off" />
            </a-form-item>
          </div>
        </a-form>
      </div>
    </a-modal>

    <a-modal v-model="advancedModal" title="高级搜索" class="mend-advanced-modal" cancelText="取消" okText="确定" @ok="handleAdvancedOk" @cancel="handleAdvancedCancel">
      <a-form :form="form">
        <div class="mend-single-row">
          <a-col span="8" className="service-form">
            <a-form-item label="所 属 片 区" class="repair-form">
              <a-select
                option-filter-prop="children"
                show-search
                style="min-width: 170px; width: auto;"
                v-decorator="['ownDistrict', { initialValue: '', rules: [{ required: false, message: '' }] }]"
                placeholder="请选择"
              >
                <a-select-option value="华中片区">华中片区</a-select-option>
                <a-select-option value="滕州分公司">滕州分公司</a-select-option>
                <a-select-option value="华东片区">华东片区</a-select-option>
                <a-select-option value="东北片区">东北片区</a-select-option>
                <a-select-option value="西北片区">西北片区</a-select-option>
                <a-select-option value="深圳分公司">深圳分公司</a-select-option>
                <a-select-option value="宁波分公司">宁波分公司</a-select-option>
                <a-select-option value="重庆分公司">重庆分公司</a-select-option>
                <a-select-option value="沈阳分公司">沈阳分公司</a-select-option>
                <a-select-option value="云南分公司">云南分公司</a-select-option>
                <a-select-option value="泉州分公司">泉州分公司</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col span="8" className="service-form">
            <a-form-item label="任 务 类 别" class="repair-form">
              <a-select
                option-filter-prop="children"
                show-search
                style="min-width: 170px; width: auto;"
                v-decorator="['taskType', { initialValue: '', rules: [{ required: false, message: '' }] }]"
                placeholder="请选择"
              >
                <a-select-option value="设备调试">设备调试</a-select-option>
                <a-select-option value="故障报修">故障报修</a-select-option>
                <a-select-option value="培训申请">培训申请</a-select-option>
                <a-select-option value="大赛技术支持">大赛技术支持</a-select-option>
                <a-select-option value="技术咨询">技术咨询</a-select-option>
                <a-select-option value="其他">其他</a-select-option>
                <a-select-option value="机床翻新">机床翻新</a-select-option>
                <a-select-option value="驻厂服务">驻厂服务</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col span="8" className="service-form">
            <a-form-item label="故 障 类 型" class="repair-form">
              <a-select
                option-filter-prop="children"
                show-search
                style="min-width: 170px; width: auto;"
                v-decorator="['impedimentType', { initialValue: '', rules: [{ required: false, message: '' }] }]"
                placeholder="请选择"
              >
                <a-select-option value="系统故障">系统故障</a-select-option>
                <a-select-option value="驱动器故障">驱动器故障</a-select-option>
                <a-select-option value="电机故障">电机故障</a-select-option>
                <a-select-option value="线缆故障">线缆故障</a-select-option>
                <a-select-option value="UPS电源故障">UPS电源故障</a-select-option>
                <a-select-option value="机械故障">机械故障</a-select-option>
                <a-select-option value="其他">其他</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </div>
        <div class="mend-single-row">
          <a-col span="8" className="service-form">
            <a-form-item label="用 户 单 位" class="repair-form">
              <a-input class="deploy-form-single-input" v-decorator="['companyName', { initialValue: '' }]" placeholder="请输入" autoComplete="off" />
            </a-form-item>
          </a-col>
          <a-col span="8" className="service-form">
            <a-form-item label="用户手机号" class="repair-form">
              <a-input class="deploy-form-single-input" v-decorator="['phoneNumber', { initialValue: '' }]" placeholder="请输入" autoComplete="off" />
            </a-form-item>
          </a-col>
          <a-col span="8" className="service-form">
            <a-form-item label="现场工程师" class="repair-form">
              <a-input class="deploy-form-single-input" v-decorator="['fieldEngineer', { initialValue: '' }]" placeholder="请输入" autoComplete="off" />
            </a-form-item>
          </a-col>
        </div>
        <div class="mend-single-row">
          <a-col span="8" className="service-form">
            <a-form-item label="故障件编号" class="repair-form">
              <a-input class="deploy-form-single-input" v-decorator="['faultyPartsNumber', { initialValue: '' }]" placeholder="请输入" autoComplete="off" />
            </a-form-item>
          </a-col>
          <a-col span="8" className="service-form">
            <a-form-item label="故障件型号" class="repair-form">
              <a-input class="deploy-form-single-input" v-decorator="['faultyPartsType', { initialValue: '' }]" placeholder="请输入" autoComplete="off" />
            </a-form-item>
          </a-col>
          <a-col span="8" className="service-form">
            <a-form-item label="机 床 厂 家" class="repair-form">
              <a-input class="deploy-form-single-input" v-decorator="['macFactory', { initialValue: '' }]" placeholder="请输入" autoComplete="off" />
            </a-form-item>
          </a-col>
        </div>
        <div class="mend-single-row">
          <a-col span="8" className="service-form">
            <a-form-item label="系 统 型 号" class="repair-form">
              <a-input class="deploy-form-single-input" v-decorator="['macSn', { initialValue: '' }]" placeholder="请输入" autoComplete="off" />
            </a-form-item>
          </a-col>
          <a-col span="8" className="service-form">
            <a-form-item label="系 统 SN 号" class="repair-form">
              <a-input class="deploy-form-single-input" v-decorator="['ncSystemType', { initialValue: '' }]" placeholder="请输入" autoComplete="off" />
            </a-form-item>
          </a-col>
        </div>
      </a-form>
      <!--<div class="mend-form-reset" @click="handleReset">重 置</div>-->
    </a-modal>
  </div>
</template>

<script>
// import FileSaver from 'file-saver'
// import XLSX from 'xlsx';
import { mapState } from 'vuex';
import api from '@/server/userConfig';
import GLOBAL from '@/api/global_variable';
import axios from 'axios';

import { downloadColumns } from './tableConfig';
import ExportFile from 'vue-json-excel';

let time = new Date().getTime() + 24 * 60 * 60 * 1000;
let tmoday = new Date(time);
tmoday = tmoday.getFullYear() + '-' + (tmoday.getMonth() > 9 ? tmoday.getMonth() + 1 : '0' + (tmoday.getMonth() + 1)) + '-' + (tmoday.getDate() > 9 ? tmoday.getDate() : '0' + tmoday.getDate());
let endTime = tmoday;

const columns = [
  {
    title: '订单类型',
    dataIndex: 'afterSaleNumber',
    width: '150px',
    key: 'afterSaleNumber',
    ellipsis: true,
    class: 'bill-order',
    scopedSlots: { customRender: 'afterSaleNumber' },
  },
  {
    title: '订单编号',
    dataIndex: 'repairOrderNumber',
    key: 'repairOrderNumber',
    width: '150px',
    ellipsis: true,
  },
  {
    title: '客户单位',
    dataIndex: 'companyName',
    key: 'companyName',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '故障描述',
    dataIndex: 'description',
    key: 'description',
    width: '250px',
    ellipsis: true,
    class: 'fault-description',
  },
  {
    title: '报修时间',
    dataIndex: 'uploadTime',
    key: 'uploadTime',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '订单状态',
    dataIndex: 'state',
    key: 'state',
    width: '150px',
    class: 'bill-state',
    ellipsis: true,
    scopedSlots: { customRender: 'state' },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: '200px',
    ellipsis: true,
    scopedSlots: { customRender: 'operation' },
  },
  {
    title: '新建工单',
    dataIndex: 'newBill',
    key: 'newBill',
    width: '120px',
    ellipsis: true,
    scopedSlots: { customRender: 'newBill' },
  },
  {
    title: '当前处理人',
    dataIndex: 'appointor',
    key: 'appointor',
    width: '150px',
    ellipsis: true,
  },
  {
    title: '报修人姓名',
    dataIndex: 'repairman',
    key: 'repairman',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '报修人电话',
    dataIndex: 'phoneNumber',
    key: 'phoneNumber',
    width: '150px',
    ellipsis: true,
  },
  {
    title: '机床型号',
    dataIndex: 'macType',
    key: 'macType',
    width: '240px',
    ellipsis: true,
  },
  {
    title: '机床编号',
    dataIndex: 'macNumb',
    key: 'macNumb',
    width: '240px',
    ellipsis: true,
  },
  {
    title: '机床厂家',
    dataIndex: 'macFactory',
    key: 'macFactory',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '机床位置',
    dataIndex: 'address',
    key: 'address',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '报修机床厂',
    dataIndex: 'repairCompany',
    key: 'repairCompany',
    width: '180px',
  },
  {
    title: '报单人员',
    dataIndex: 'role',
    key: 'role',
    width: '120px',
    ellipsis: true,
  },
  {
    title: '设备购买时间',
    dataIndex: 'purchaseTime',
    key: 'purchaseTime',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '详细地址',
    dataIndex: 'fullAddress',
    key: 'fullAddress',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '系统型号',
    dataIndex: 'ncSystemType',
    key: 'ncSystemType',
    width: '180px',
    class: 'hello',
    ellipsis: true,
  },
  {
    title: '所属片区',
    dataIndex: 'secondDepartment',
    key: 'secondDepartment',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '任务类别',
    dataIndex: 'taskType',
    key: 'taskType',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '设备类型',
    dataIndex: 'equipmentType',
    key: 'equipmentType',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '保修状态',
    dataIndex: 'guaranteeState',
    key: 'guaranteeState',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '客户类型',
    dataIndex: 'customerType',
    key: 'customerType',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '信息来源',
    dataIndex: 'informationSource',
    key: 'informationSource',
    class: 'hello',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '数控系统编号',
    dataIndex: 'ncNumber',
    key: 'ncNumber',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '数控系统版本',
    dataIndex: 'ncVersionType',
    key: 'ncVersionType',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '数控系统SN',
    dataIndex: 'macSn',
    key: 'macSn',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '故障件型号',
    dataIndex: 'faultyPartsType',
    key: 'faultyPartsType',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '故障件编号',
    dataIndex: 'faultyPartsNumber',
    key: 'faultyPartsNumber',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '故障件使用时间',
    dataIndex: 'faultyPartsTime',
    key: 'faultyPartsTime',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '处理时间',
    dataIndex: 'resolveTime',
    key: 'resolveTime',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '加班时间',
    dataIndex: 'extraTime',
    key: 'extraTime',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '设备处理数量',
    dataIndex: 'resolveNcNumber',
    key: 'resolveNcNumber',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '是否重大问题',
    dataIndex: 'isViIssue',
    key: 'isViIssue',
    width: '180px',
    ellipsis: true,
    scopedSlots: { customRender: 'isViIssue' },
  },
  {
    title: '故障发生时间',
    dataIndex: 'impedimentStartTime',
    key: 'impedimentStartTime',
    width: '180px',
  },
  {
    title: '故障类型',
    dataIndex: 'impedimentType',
    key: 'impedimentType',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '故障分类',
    dataIndex: 'faultClass',
    key: 'faultClass',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '故障原因',
    dataIndex: 'impedimentReason',
    key: 'impedimentReason',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '故障处理结果',
    dataIndex: 'impedimentResolveResult',
    key: 'impedimentResolveResult',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '现场服务工程师',
    dataIndex: 'fieldEngineer',
    key: 'fieldEngineer',
    width: '150px',
    ellipsis: true,
  },
  {
    title: '需求建议',
    dataIndex: 'demandSuggestion',
    key: 'demandSuggestion',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '其他描述',
    dataIndex: 'otherDescription',
    key: 'otherDescription',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '解决方案',
    dataIndex: 'solution',
    key: 'solution',
    width: '150px',
    ellipsis: true,
  },
  {
    title: '重大专项课题名称',
    dataIndex: 'topicName',
    key: 'topicName',
    width: '150px',
    ellipsis: true,
  },
  {
    title: '重大专项课题编号',
    dataIndex: 'topicNumber',
    key: 'topicNumber',
    width: '150px',
    ellipsis: true,
  },
  {
    title: '重大专项应用领域',
    dataIndex: 'applicationRange',
    key: 'applicationRange',
    width: '180px',
    ellipsis: true,
  },
  {
    title: '服务满意度',
    dataIndex: 'serviceScore',
    key: 'serviceScore',
    width: '150px',
  },
  {
    title: '服务回访备注',
    dataIndex: 'serviceEvaluate',
    key: 'serviceEvaluate',
    width: '150px',
    ellipsis: true,
  },
  {
    title: '产品满意度',
    dataIndex: 'produceScore',
    key: 'produceScore',
    width: '150px',
  },
  {
    title: '产品回访备注',
    dataIndex: 'produceEvaluate',
    key: 'produceEvaluate',
    width: '150px',
    ellipsis: true,
  },
];

function buildJsonFields(lists) {
  let jsonFields = {};
  lists.forEach((item, index) => {
    if (item.dataIndex) {
      jsonFields[item.title] = item.dataIndex;
    }
  });
  return jsonFields;
}

export default {
  name: 'MendTableContainer',
  components: {
    ExportFile,
  },
  data() {
    //this.cacheData = data.map(item => ({ ...item }));
    return {
      role: -1,
      tableData: [],
      columns: columns,
      editingKey: '',
      visible: false,
      username: '',
      isLoading: false,
      isSearchShow: true,
      repairOrderNumber: '',
      afterSaleNumber: '',
      dispatchName: '',
      record: {},
      dispatchPhone: '',
      transferPhone: '',
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      dispatchList: [{ name: '', id: 23, phone: '' }],
      transferList: [{ name: '', id: 23, phone: '' }],
      pagination: {
        page: 1,
        pageSize: 8, // 默认每页显示数量
        total: 0, // 总数量;
        showTotal: (total) => `共 ${total} 条`, // 显示总数
        current: 1,
        defaultCurrent: 1,
        pageSizeOptions: ['5', '10', '15', '20'],
        onShowSizeChange: (page, pageSize) => (this.pageSize = pageSize),
      },
      billTypeValue: '全部',
      finishTypeValue: '',
      stateTypeValue: '-1',
      searchInput: '',
      advancedSearchValue: '',
      advancedModal: false,
      evaluateModel: false,
      innerModel: false,
      transferModel: false,
      finishModel: false,
      values: {},
      count: 4,
      serviceScore: 4,
      serviceDesc: ['不满意', '一般', '满意', '很满意'],
      produceScore: 4,
      produceDesc: ['不满意', '一般', '满意', '很满意'],
      currentPage: 1,
      form: this.$form.createForm(this, { name: 'dynamic_rule' }),
      evaluateForm: this.$form.createForm(this, { name: 'evaluate_form' }),
      transferForm: this.$form.createForm(this, { name: 'transfer_form' }),
      iconLoading: false,
      jsonFields: buildJsonFields(downloadColumns),
    };
  },
  computed: {
    firstDispatchData: function() {
      return this.dispatchList[0].name;
    },
    ...mapState(['roleId']),
  },
  watch: {
    role: function(newVal) {
      if (newVal !== -1) {
        this.getDistrictList(this.username);
        this.getTransferList(this.username);
      }
    },
  },
  created() {
    // 获取链接参数username值，然后存进内存中
    this.username = localStorage.getItem('phone');
  },
  mounted() {
    //this.getDistrictList(this.username);
    //this.getTransferList(this.username);
    this.getRoleId();
    /*'http://10.10.56.153:8021/cloudManagerApi/getRepairOrderByStateAndPage.action?state=-1&startTime=2017-01-01&endTime=2020-07-15' +
      '&param=all&username=18392152392&pageIndex=126&pageSize=8';*/
    let pageIndex = 1;
    this.getMendList(
      GLOBAL.localIp + '/getRepairOrderByStateAndPage.action?state=-1&startTime=2017-01-01' + '&endTime=' + endTime + '&param=all&username=' + this.username + '&pageIndex=' + pageIndex + '&pageSize=8'
    );
  },
  methods: {
    // 点击搜索按钮;
    searchParam() {
      const param = this.searchInput;
      if (!param) {
        this.$message.info('请输入搜索关键词');
        return;
      }
      let pageIndex = 1;
      const url = GLOBAL.localIp + '/getRepairOrderByParamAndPage.action?param=' + param + '&username=' + this.username + '&pageIndex=' + pageIndex + '&pageSize=10';
      this.getMendList(url);
      this.stateTypeValue = '全部';
    },
    // 点击高级搜索;
    handleAdvancedSearch() {
      this.advancedModal = true;
    },
    // 点击高级搜索的确定;
    handleAdvancedOk() {
      this.form.validateFields((err, values) => {
        console.log(values);
        this.values = values;
        if (
          values.ownDistrict === '' &&
          values.taskType === '' &&
          values.macSn === '' &&
          values.faultyPartsType === '' &&
          values.faultyPartsNumber === '' &&
          values.impedimentType === '' &&
          values.phoneNumber === '' &&
          values.companyName === '' &&
          values.ncSystemType === '' &&
          values.macFactory === '' &&
          values.fieldEngineer === ''
        ) {
          this.advancedModal = false;
          this.$message.info('用户未进行高级搜索');
        } else {
          // 需要重置之前选中的;
          this.billTypeValue = '全部';
          this.finishTypeValue = '';
          this.stateTypeValue = '-1';
          this.searchInput = '';
          this.advancedSearchValue = 'all';
          // 发送ajax请求;
          let pageIndex = 1;
          let pageSize = 5;
          this.pagination.current = 1;
          const url =
            GLOBAL.localIp +
            '/getAfterSaleByParamAndPage.action?ownDistrict=' +
            values.ownDistrict +
            '&informationSource=&resolveTime=&taskType=' +
            values.taskType +
            '&ncNumber=&extraTime=&equipmentType=' +
            '&ncVersionType=&resolveNcNumber=&guaranteeState=&macSn=' +
            values.macSn +
            '&customerType=' +
            '&faultyPartsType=' +
            values.faultyPartsType +
            '&uploadTime=&faultyPartsTime=&faultyPartsNumber=' +
            values.faultyPartsNumber +
            '&impedimentType=' +
            values.impedimentType +
            '&username=' +
            this.username +
            '&phoneNumber=' +
            values.phoneNumber +
            '&companyName=' +
            values.companyName +
            '&ncSystemType=' +
            values.ncSystemType +
            '&macFactory=' +
            values.macFactory +
            '&fieldEngineer=' +
            values.fieldEngineer +
            '&pageIndex=' +
            pageIndex +
            '&pageSize=' +
            pageSize;
          this.advancedModal = false;
          this.form.resetFields();
          this.getMendList(url);
        }
      });
    },
    // 点击重置
    handleReset() {
      this.form.resetFields();
    },
    // 点击取消, 也要重置;
    handleAdvancedCancel() {
      this.form.resetFields();
      this.advancedModal = false;
    },
    // 切换订单类型;
    async handleBillChange(value) {
      console.log(`selected ${value}`);
      let pageIndex = 1;
      this.pagination.current = 1;
      this.billTypeValue = value;
      this.finishTypeValue = '';
      // 清空输入框, 同时把订单状态切换到全部, 同时把高级搜索的也去掉;
      this.searchInput = '';
      this.stateTypeValue = '-1';
      this.advancedSearchValue = '';
      let url = '';
      if (value === '我的') {
        url = GLOBAL.localIp + '/getRepairOrderByDistrictAndPage.action?' + 'username=' + this.username + '&pageIndex=' + pageIndex + '&pageSize=8';
        this.isSearchShow = true;
      } else if (value === 'all') {
        url =
          GLOBAL.localIp +
          '/getRepairOrderByStateAndPage.action?state=-1&startTime=2017-01-01' +
          '&endTime=' +
          endTime +
          '&param=all&username=' +
          this.username +
          '&pageIndex=' +
          pageIndex +
          '&pageSize=8';
        this.isSearchShow = true;
      } else if (value === '研究院工单') {
        // url = GLOBAL.localIp + "/getAfterSaleOfInstitute.action?pageIndex="+pageIndex+"&pageSize=8";
        url = GLOBAL.localIp + '/getAfterSaleOfInstitute.action?username=' + this.username + '&pageIndex=' + pageIndex + '&pageSize=8';
        this.isSearchShow = false;
      }
      this.getMendList(url);
    },
    // 切换完成状态;
    handleFinishChange(value) {
      console.log(value);
      this.finishTypeValue = value;
      this.pagination.current = 1;
      this.billTypeValue = '全部';
      this.stateTypeValue = '-1';
      this.searchInput = '';
      this.advancedSearchValue = '';
      let url = '';
      if (value === '已完成订单') {
        // 调用接口;
        url = GLOBAL.localIp + '/faultRepairCompleteListAndPage.action?username=' + this.username + '&pageIndex=1&pageSize=8';
      } else if (value === '未完成订单') {
        url = GLOBAL.localIp + '/faultRepairIncompleteListAndPage.action?username=' + this.username + '&pageIndex=1&pageSize=8';
      }
      this.getMendList(url);
    },
    // 切换订单状态;
    handleStateChange(value) {
      this.stateTypeValue = value;
      this.pagination.current = 1;
      this.billTypeValue = '全部';
      this.finishTypeValue = '';
      this.searchInput = '';
      this.advancedSearchValue = '';
      console.log(this.finishTypeValue);
      // 调用接口;
      let pageIndex = 1;
      this.getMendList(
        GLOBAL.localIp +
          '/getRepairOrderByStateAndPage.action?state=' +
          value +
          '&startTime=2017-01-01' +
          '&endTime=' +
          endTime +
          '&param=all&username=' +
          this.username +
          '&pageIndex=' +
          pageIndex +
          '&pageSize=8'
      );
    },
    // 获取维修单列表;
    getMendList(url) {
      console.log(url);
      this.isLoading = true;
      axios.get(url).then((res) => {
        console.log('getMendList            ', res.data);
        const init_data = res.data.Data.content;
        const total = res.data.Data.total;
        this.isLoading = false;
        this.initTriggerData(init_data, total);
      });
    },
    // 重组维修单数据;
    initTriggerData(init_data, total) {
      let newData = [];
      if (init_data) {
        const initDataLength = init_data.length;
        for (let i = 0; i < initDataLength; i++) {
          if (init_data[i].evaluation == null) {
            init_data[i].serviceScore = ''; // 新增服务满意度;
            init_data[i].serviceEvaluate = ''; // 新增服务回访备注;
            init_data[i].produceScore = ''; // 新增产品满意度;
            init_data[i].produceEvaluate = ''; // 新增产品回访备注;
          } else if (init_data[i].evaluation != null) {
            init_data[i].serviceScore = init_data[i].evaluation.serviceScore + '分'; // 新增服务满意度;
            init_data[i].serviceEvaluate = init_data[i].evaluation.serviceEvaluate; // 新增服务回访备注;
            init_data[i].produceScore = init_data[i].evaluation.produceScore + '分'; // 新增产品满意度;
            init_data[i].produceEvaluate = init_data[i].evaluation.produceEvaluate; // 新增产品回访备注;
          }
          if (init_data[i].afterSaleService == null) {
            //代表是客户服务单；还没有售后数据;
            newData.push({
              saleNumber: '客户服务单',
              repairOrderNumber: init_data[i].repairList.repairOrderNumber,
              appointor: init_data[i].appointor, // 新增当前处理人;
              serviceScore: '', // 新增服务满意度;
              serviceEvaluate: '', // 新增服务回访备注;
              produceScore: '', // 新增产品满意度;
              produceEvaluate: '', // 新增产品回访备注;
              address: init_data[i].repairList.address,
              companyName: init_data[i].repairList.companyName,
              description: init_data[i].repairList.description,
              uploadTime: init_data[i].repairList.uploadTime,
              purchaseTime: init_data[i].repairList.purchaseTime,
              macFactory: init_data[i].repairList.macFactory,
              state: init_data[i].repairList.state,
              afterSaleNumber: '',

              fullAddress: init_data[i].repairList.fullAddress, // 新增详细地址
              repairCompany: init_data[i].repairList.repairCompany, // 报修机床厂;
              role: init_data[i].role, // 报单人员;
              repairman: init_data[i].repairList.repairman, //报修人姓名
              phoneNumber: init_data[i].repairList.phoneNumber, //报修人电话
              macType: init_data[i].repairList.macType, //机床型号
              macNumb: init_data[i].repairList.macNumb, //机床编号
              ncSystemType: init_data[i].repairList.ncSystemType, //系统型号，以上是客户单;
              suit: init_data[i].suit, // 是否是本人关联的单子
              secondDepartment: '', //所属片区;
              taskType: '', //任务类别;
              equipmentType: '', //设备类型;
              guaranteeState: '', //保修状态；
              customerType: '', //客户类型；
              informationSource: '', //信息来源；
              ncNumber: '', //数控系统编号；
              ncVersionType: '', // 数控系统版本
              macSn: '', //数控系统SN；
              impedimentType: '', //故障类型；
              faultClass: '', //故障分类；
              impedimentReason: '', //故障原因；
              impedimentResolveResult: '', //故障处理结果；
              impedimentStartTime: '', //故障发生时间；
              impedimentDescri: '', //故障详细描述；
              faultyPartsType: '', //故障件型号；
              faultyPartsNumber: '', //故障件编号；
              faultyPartsTime: '', //故障件使用时间；
              fieldEngineer: '', //现场服务工程师；
              resolveTime: '', //处理时间；
              extraTime: '', //加班时间；
              resolveNcNumber: '', //设备处理数量；
              isViIssue: '', //是否重大问题；
              viIssueInfo: '', // 重大问题的具体内容,
              demandSuggestion: '', // 需求建议,
              otherDescription: '', // 其他描述,
              solution: '', // 解决方案,
              topicName: '', // 重大专项课题名称,
              topicNumber: '', // 重大专项课题编号,
              applicationRange: '', // 重大专项应用领域,
            });
          } else if (init_data[i].afterSaleService) {
            //代表是客户服务单；还没有售后数据;
            newData.push({
              saleNumber: '华中售后单',
              appointor: init_data[i].appointor,
              serviceScore: init_data[i].serviceScore,
              serviceEvaluate: init_data[i].serviceEvaluate,
              produceScore: init_data[i].produceScore,
              produceEvaluate: init_data[i].produceEvaluate,
              address: init_data[i].repairList.address || '',
              companyName: init_data[i].repairList.companyName || '', //****
              description: init_data[i].repairList.description || '', // ****
              state: init_data[i].afterSaleService.impedimentState || '', // ****
              repairman: init_data[i].repairList.repairman || '', //报修人姓名
              phoneNumber: init_data[i].repairList.phoneNumber || '', //报修人电话
              fullAddress: init_data[i].repairList.fullAddress, // 新增详细地址
              repairCompany: init_data[i].repairList.repairCompany, // 报修机床厂;
              role: init_data[i].role, // 报单人员;

              macFactory: init_data[i].repairList.macFactory || '', //机床厂家
              macType: init_data[i].repairList.macType || '', //机床型号
              macNumb: init_data[i].repairList.macNumb || '', //机床编号
              purchaseTime: init_data[i].repairList.purchaseTime || '',
              ncSystemType: init_data[i].repairList.ncSystemType || '', //系统型号，以上是客户单；
              uploadTime: init_data[i].repairList.uploadTime || '', // 报修时间;
              repairOrderNumber: init_data[i].afterSaleService.repairOrderNumber,
              afterSaleNumber: init_data[i].afterSaleService.afterSaleNumber,
              secondDepartment: init_data[i].afterSaleService.secondDepartment, //所属片区；
              taskType: init_data[i].afterSaleService.taskType, //任务类别；
              equipmentType: init_data[i].afterSaleService.equipmentType, //设备类型；
              guaranteeState: init_data[i].afterSaleService.guaranteeState, //保修状态；
              customerType: init_data[i].afterSaleService.customerType, //客户类型；
              informationSource: init_data[i].afterSaleService.informationSource, //信息来源；
              ncNumber: init_data[i].afterSaleService.ncNumber, //数控系统编号；
              ncVersionType: init_data[i].afterSaleService.ncVersionType, // 数控系统版本
              macSn: init_data[i].afterSaleService.macSn, //数控系统SN；
              impedimentType: init_data[i].afterSaleService.impedimentType, //故障类型；
              faultClass: init_data[i].afterSaleService.faultClass, //故障分类；
              impedimentReason: init_data[i].afterSaleService.impedimentReason, //故障原因；
              impedimentResolveResult: init_data[i].afterSaleService.impedimentResolveResult, //故障处理结果；
              impedimentStartTime: init_data[i].afterSaleService.impedimentStartTime, //故障发生时间；
              impedimentDescri: init_data[i].afterSaleService.impedimentDescri, //故障详细描述；
              faultyPartsType: init_data[i].afterSaleService.faultyPartsType, //故障件型号；
              faultyPartsNumber: init_data[i].afterSaleService.faultyPartsNumber, //故障件编号；
              faultyPartsTime: init_data[i].afterSaleService.faultyPartsTime, //故障件使用时间；
              fieldEngineer: init_data[i].afterSaleService.fieldEngineer, //现场服务工程师；
              resolveTime: init_data[i].afterSaleService.resolveTime, //处理时间；
              extraTime: init_data[i].afterSaleService.extraTime, //加班时间；
              resolveNcNumber: init_data[i].afterSaleService.resolveNcNumber, //设备处理数量；
              isViIssue: init_data[i].afterSaleService.isViIssue, //是否重大问题;
              viIssueInfo: init_data[i].afterSaleService.viIssueInfo, // 重大问题的具体内容
              suit: init_data[i].suit, // 是否是本人关联的单子,
              demandSuggestion: init_data[i].afterSaleService.demandSuggestion, // 需求建议,
              otherDescription: init_data[i].afterSaleService.otherDescription, // 其他描述,
              solution: init_data[i].afterSaleService.solution, // 解决方案,
              topicName: init_data[i].afterSaleService.topicName, // 重大专项课题名称,
              topicNumber: init_data[i].afterSaleService.topicNumber, // 重大专项课题编号,
              applicationRange: init_data[i].afterSaleService.applicationRange, // 重大专项应用领域,
            });
          }
          init_data[i].saleNumber = init_data[i].afterSaleNumber;
        }
      } else {
        newData = [];
      }
      for (let j = 0; j < newData.length; j++) {
        newData[j].key = newData[j].repairOrderNumber;
      }
      this.tableData = newData;
      this.pagination.total = total;
    },
    // 点击每一行的跳转;
    clickSingleRow(record, index) {
      return {
        on: {
          click: () => {
            console.log(record, index);
            // 实现跳转;
            //this.$router.push(`/index/detail/${record.repairOrderNumber}`)
            //window.open(`/#/index/clientDetail/${record.repairOrderNumber}`);
            if (record.afterSaleNumber !== '') {
              window.open(`/#/index/mend/sale/${record.repairOrderNumber}/${record.afterSaleNumber}/${record.suit}`);
            } else {
              window.open(`/#/index/mend/client/${record.repairOrderNumber}`);
            }
          },
        },
      };
    },
    // 获取转单列表;
    async getTransferList(username) {
      const res = await api.getDistrictList({ username: username });
      if (res.MsgCode !== 0) {
        return;
      }
      this.transferList = [...res.Data];
      // const res = await api.reqTransferList({username: username});
      // console.log(res);
      // if(res.MsgCode !== 0){
      //   return;
      // }
    },
    // 获取指派列表;
    async getDistrictList(username) {
      if (this.role === 17 || this.role === 19) {
        const res = await api.getDistrictList({ username: username });
        //console.log(res);
        if (res.MsgCode !== 0) {
          return;
        }
        const result = res.Data;
        let nameArray = [];
        const dispatchLength = result.length;
        for (let i = 0; i < dispatchLength; i++) {
          nameArray.push({
            name: result[i].name,
            phone: result[i].phone,
            id: result[i].iD,
            username: result[i].username,
          });
        }
        //console.log(nameArray);
        this.dispatchList = nameArray;
        this.dispatchName = nameArray[0].name;
        this.dispatchPhone = nameArray[0].username;
      } else {
        const res = await api.getDispatchList({ username: username });
        if (res.MsgCode !== 0) {
          return;
        }
        //console.log(res);
        const result = res.Data;
        let nameArray = [];
        const dispatchLength = result.length;
        for (let i = 0; i < dispatchLength; i++) {
          nameArray.push({
            name: result[i].name,
            phone: result[i].phone,
            id: result[i].iD,
            username: result[i].username,
          });
        }
        //console.log(nameArray);
        this.dispatchList = nameArray;
        this.dispatchName = nameArray[0].name;
        this.dispatchPhone = nameArray[0].username;
      }
    },
    // 点击删除工单
    handleDelete(record) {
      this.$Modal.confirm({
        title: '确认删除此工单吗?',
        content: '',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          const res = await api.reqDeleteBill({ repairOrderNumber: record.repairOrderNumber });
          if (res.MsgCode === 0) {
            this.$Modal.success({
              title: '',
              content: '删除成功!',
              okText: '确定',
              onOk: () => {
                this.handleAllPageChange();
              },
            });
          }
        },
        onCancel() {},
      });
    },
    //点击新建工单;
    handleNewBill(record) {
      window.open(`/#/index/mend/new/${record.repairOrderNumber}`);
    },
    // 点击工单指派;
    handleDispatch(record) {
      console.log(record);
      this.visible = true;
      this.repairOrderNumber = record.repairOrderNumber;
      this.record = record;
    },
    // 点击工单指派的确定;
    async handleDispatchOk() {
      this.visible = false;
      // 发送ajax请求;
      const res = await api.reqHandleDispatch({
        appointor: this.dispatchName,
        phoneNumber: this.dispatchPhone,
        repairOrderNumber: this.repairOrderNumber,
      });
      if (res.MsgCode === 0) {
        this.$Modal.success({
          title: '',
          content: '指派成功!',
          okText: '确定',
          onOk: () => {
            this.handleAllPageChange();
          },
        });
      } else {
        this.$message.error('指派失败...');
      }
      // 同时给报修人发短信;
      const dispatchMsg = await api.reqSendDispatchMsg({
        name: this.dispatchName,
        phone: this.dispatchPhone,
        reportNo: this.repairOrderNumber,
        reportPersonPhone: this.record.phoneNumber,
      });
      if (dispatchMsg.data.state === '000000') {
        this.$message.success('短信发送成功!');
      }
      // 同时再给维修人发短信;
      const dispatchMsg1 = await api.reqSendMendMsg({
        name: this.record.repairman,
        phone: this.dispatchPhone,
        companyName: this.record.companyName,
        reportNo: this.repairOrderNumber,
        reportPersonPhone: this.record.phoneNumber,
      });
      if (dispatchMsg1.data.state !== '000000') {
        return;
      }
    },
    // 点击维修完成;
    handleFinish(record) {
      this.finishModel = true;
      this.afterSaleNumber = record.afterSaleNumber;
    },
    // 点击维修完成的确定;
    async handleFinishOk() {
      this.finishModel = false;
      // 发送请求;
      const res = await api.reqMendFinish({
        afterSaleNumber: this.afterSaleNumber,
        state: 5,
        username: this.username,
      });
      console.log(res);
      if (res.MsgCode === 0) {
        this.$Modal.success({
          title: '',
          content: '维修完成!',
          okText: '确定',
          onOk: () => {
            this.handleAllPageChange();
          },
        });
      }
    },
    // 点击维修完成的cancel;
    handleFinishCancel() {
      this.finishModel = false;
    },
    // 点击转单;
    handleTransfer(record) {
      this.transferModel = true;
      this.record = record;
      this.repairOrderNumber = record.repairOrderNumber;
    },
    // 点击转单的取消;
    handleTransferCancel() {
      //this.transferForm.resetFields();
    },
    // 点击转单的确定;
    handleTransferOk() {
      this.transferForm.validateFields(async (err, values) => {
        // 发送ajax请求;
        let accurateRepairMan;
        for (let i = 0; i < this.transferList.length; i++) {
          if (this.transferList[i].iD === values.repairMan) {
            accurateRepairMan = this.transferList[i].name;
          }
        }
        const res = await api.reqTransferBill({
          repairMan: accurateRepairMan,
          phoneNumber: values.phoneNumber,
          repairOrderNumber: this.repairOrderNumber,
        });
        this.transferForm.resetFields();
        this.transferModel = false;
        if (res.MsgCode === 0) {
          this.$Modal.success({
            title: '',
            content: '转单成功!',
            okText: '确定',
            onOk: () => {
              this.handleAllPageChange();
            },
          });
        } else {
          this.$message.error('转单失败...');
        }
        // 同时给转单的人员发短信;
        const transferMsg = await api.reqSendTransferMsg({
          name: this.record.repairman,
          phone: values.phoneNumber,
          companyName: this.record.companyName,
          reportNo: this.repairOrderNumber,
          reportPersonPhone: this.record.phoneNumber,
        });
        if (transferMsg.data.state === '000000') {
          this.$message.success('短信发送成功!');
        }
      });
    },
    // 点击评价;
    handleEvaluate(record) {
      this.evaluateModel = true;
      this.repairOrderNumber = record.repairOrderNumber;
    },
    handleEvaluateCancel() {
      this.serviceScore = 4;
      this.produceScore = 4;
      this.evaluateForm.resetFields();
    },
    // 点击评价弹出框的确定;
    handleEvaluateOk() {
      this.evaluateForm.validateFields((err, values) => {
        let newData = {};
        newData.produceScore = this.produceScore;
        newData.serviceScore = this.serviceScore;
        newData.repairOrderNumber = this.repairOrderNumber;
        newData.serviceEvaluate = values.serviceEvaluate;
        newData.produceEvaluate = values.produceEvaluate;
        newData.username = this.username;
        const jsonData = JSON.stringify(newData);
        console.log(newData);
        // 发送ajax请求;
        api.reqHandleEvaluate(jsonData).then((res) => {
          if (res.MsgCode === 0) {
            this.$Modal.success({
              title: '',
              content: '评价成功!',
              okText: '确定',
              onOk: () => {
                this.handleAllPageChange();
                this.evaluateForm.resetFields();
                this.produceScore = 4;
                this.serviceScore = 4;
              },
            });
          } else {
            this.$message.error('评价失败...');
          }
        });
        this.evaluateModel = false;
      });
    },
    // 点击内部关闭;
    handleInnerClose(record) {
      this.innerModel = true;
      this.afterSaleNumber = record.afterSaleNumber;
    },
    // 点击内部关闭的确定;
    async handleInnerCloseOk() {
      this.innerModel = false;
      // 发送请求;
      const res = await api.reqInnerClose({
        afterSaleNumber: this.afterSaleNumber,
        state: 10,
        username: this.username,
      });
      if (res.MsgCode === 0) {
        this.$Modal.success({
          title: '',
          content: '内部关闭成功!',
          okText: '确定',
          onOk: () => {
            this.handleAllPageChange();
          },
        });
      }
    },
    // 点击内部关闭的cancel;
    handleInnerCancel() {
      this.innerModel = false;
    },
    // 点击表格分页;
    tableChange(page) {
      this.currentPage = page.current;
      this.pagination.current = page.current;
      this.pagination.defaultCurrent = page.current;
      this.handleAllPageChange();
    },
    // 处理各种状态选中的表格分页情况;
    handleAllPageChange() {
      let url = '';
      if (this.billTypeValue === '我的') {
        url = GLOBAL.localIp + '/getRepairOrderByDistrictAndPage.action?' + 'username=' + this.username + '&pageIndex=' + this.currentPage + '&pageSize=8';
      } else if (this.billTypeValue === '研究院工单') {
        url = GLOBAL.localIp + '/getAfterSaleOfInstitute.action?username=' + this.username + '&pageIndex=' + this.currentPage + '&pageSize=8';
      } else if (this.stateTypeValue !== '-1') {
        // 调用订单状态筛选接口;
        url =
          GLOBAL.localIp +
          '/getRepairOrderByStateAndPage.action?state=' +
          this.stateTypeValue +
          '&startTime=2017-01-01' +
          '&endTime=' +
          endTime +
          '&param=all&username=' +
          this.username +
          '&pageIndex=' +
          this.currentPage +
          '&pageSize=8';
      } else if (this.finishTypeValue === '已完成订单') {
        // 调用完成状态筛选接口;
        url = GLOBAL.localIp + '/faultRepairCompleteListAndPage.action?username=' + this.username + '&pageIndex=' + this.currentPage + '&pageSize=8';
      } else if (this.finishTypeValue === '未完成订单') {
        // 调用完成状态筛选接口;
        url = GLOBAL.localIp + '/faultRepairIncompleteListAndPage.action?username=' + this.username + '&pageIndex=' + this.currentPage + '&pageSize=8';
      } else if (this.searchInput !== '') {
        // 调用模糊搜索接口;
        url = GLOBAL.localIp + '/getRepairOrderByParamAndPage.action?param=' + this.searchInput + '&username=' + this.username + '&pageIndex=' + this.currentPage + '&pageSize=10';
      } else if (this.advancedSearchValue === 'all') {
        // 调用高级搜索接口;
        const values = this.values;
        url =
          GLOBAL.localIp +
          '/getAfterSaleByParamAndPage.action?ownDistrict=' +
          values.ownDistrict +
          '&informationSource=&resolveTime=&taskType=' +
          values.taskType +
          '&ncNumber=&extraTime=&equipmentType=' +
          '&ncVersionType=&resolveNcNumber=&guaranteeState=&macSn=' +
          values.macSn +
          '&customerType=' +
          '&faultyPartsType=' +
          values.faultyPartsType +
          '&uploadTime=&faultyPartsTime=&faultyPartsNumber=' +
          values.faultyPartsNumber +
          '&impedimentType=' +
          values.impedimentType +
          '&username=' +
          this.username +
          '&phoneNumber=' +
          values.phoneNumber +
          '&companyName=' +
          values.companyName +
          '&ncSystemType=' +
          values.ncSystemType +
          '&macFactory=' +
          values.macFactory +
          '&fieldEngineer=' +
          values.fieldEngineer +
          '&pageIndex=' +
          this.currentPage +
          '&pageSize=5';
      } else {
        url =
          GLOBAL.localIp +
          '/getRepairOrderByStateAndPage.action?state=-1&startTime=2017-01-01' +
          '&endTime=' +
          endTime +
          '&param=all&username=' +
          this.username +
          '&pageIndex=' +
          this.currentPage +
          '&pageSize=8';
      }
      this.getMendList(url);
    },
    // 工单指派的select
    handleDispatchChange(value) {
      const compareList = this.dispatchList;
      for (let i = 0; i < compareList.length; i++) {
        if (value === compareList[i].id) {
          this.dispatchName = compareList[i].name;
          this.dispatchPhone = compareList[i].username;
        }
      }
    },
    // 工单转单的select
    handleTransferChange(value) {
      const compareList = this.transferList;
      for (let i = 0; i < compareList.length; i++) {
        if (value === compareList[i].iD) {
          this.transferPhone = compareList[i].username;
          this.transferForm.setFieldsValue({ phoneNumber: compareList[i].username });
        }
      }
    },
    handleBlur() {},
    handleFocus() {},
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    // 根据登陆的手机号获取角色id;
    async getRoleId() {
      if (this.username !== '') {
        const res = await api.getRoleId({ phoneNumber: this.username });
        if (res.MsgCode !== 0) {
          return;
        }
        const roleId = res.Data.ID;
        this.role = roleId;
      }
    },
    // 导出表格;
    // exportExcel() {
    //   this.pagination.pageSize = this.allMendData.length; //表格长度变长
    //   this.$nextTick(function() {
    //     var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
    //     let wb = XLSX.utils.table_to_book(document.querySelector('#mendListTable'), xlsxParam);
    //     let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
    //     try {
    //       // FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '维修单列表.xlsx');
    //     } catch (e) {
    //       if (typeof console !== 'undefined') console.log(e, wbout);
    //     }
    //     this.pagination.pageSize = '10'; //表格还原
    //     return wbout;
    //   });
    // },

    // 获取需要导出的数据
    async getDownloadData() {
      let _this = this;
      if (_this.iconLoading == true) {
        return false;
      }

      let total = _this.pagination.total;
      let pageSize = 300;
      let length = Math.ceil(total / pageSize);
      let value = _this.billTypeValue;
      let lists = [];

      _this.iconLoading = true;
      if (value === '我的') {
        lists = await getOrderLists(api.getRepairOrderByDistrictAndPage, {
          length,
          apiParams: {
            pageSize: pageSize,
            username: _this.username,
          },
        });
      } else if (value === '全部' || value === 'all') {
        lists = await getOrderLists(api.getRepairOrderByStateAndPage, {
          length,
          apiParams: {
            state: -1,
            param: 'all',
            pageSize: pageSize,
            username: _this.username,
            startTime: '2017-01-01',
            endTime: endTime,
          },
        });
      } else if (value === '研究院工单') {
        lists = await getOrderLists(api.getAfterSaleOfInstitute, {
          length,
          apiParams: {
            pageSize: pageSize,
            username: _this.username,
          },
        });
      }
      _this.iconLoading = false;
      return lists;

      async function getOrderLists(func, params) {
        let { length, apiParams } = params;
        let newLists = [];
        for (let i = 1; i <= length; i++) {
          let res = await func({
            pageIndex: i,
            ...apiParams,
          });
          newLists.push(buildLists(res.Data.content));
        }
        return [].concat(...newLists);
      }

      function buildLists(lists) {
        return lists.map((item, index) => {
          try {
            let newItem = format(item);
            return newItem;
          } catch (e) {
            console.log(e);
          }
        });
      }

      function format(item) {
        if (item.repairList && item.repairList.repairOrderNumber) {
          item.repairList.repairOrderNumber = `'${item.repairList.repairOrderNumber}'`;
        }
        if (item.repairList && item.repairList.state) {
          item.repairList.state = formatState(item.repairList.state);
        }
        if (item.evaluation && item.evaluation.serviceScore) {
          item.evaluation.serviceScore += '分';
        }
        if (item.evaluation && item.evaluation.produceScore) {
          item.evaluation.produceScore += '分';
        }
        if (item.afterSaleService && item.afterSaleService.isViIssue) {
          item.afterSaleService.isViIssue = item.afterSaleService.isViIssue == 'true' ? '是' : '否';
        }
        return item;
      }

      function formatState(state) {
        switch (state) {
          case 1:
            return '已报单';
          case 2:
            return '已指派';
          case 4:
            return '已关闭';
          case 5:
            return '待回访';
          case 6:
            return '已关闭';
          case 8:
            return '进行中';
          case 9:
            return '工单暂停';
          case 10:
            return '内部已关闭';
          case 11:
            return '已指派';
          default:
            break;
        }
      }
    },
  },
};
</script>

<style lang="css" scoped>
@import './style.css';
</style>
